/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.network;
import  java.io.*;
import  java.net.*;
import com.cse.p2p.common.*;
import com.cse.p2p.database.*;
import com.cse.p2p.hash.*;
import com.cse.p2p.localfile.*;
import com.cse.p2p.parser.*;
import java.util.HashMap;
import server.dicfile.DicFileGenerating;
/**
 *
 * @author TuyetNgan
 */
public class ServerSendDataTask extends  Thread{
     private File file;
        private int portNumber = CommonSettings.CLIENT_DATA_SERVERSOCKET;
        private Socket socket = null;
        private OutputStream os = null;
    
        public ServerSendDataTask(File f,int port) {
            this.file = f;
            this.portNumber = port;
        }
        public void  newConnection(){
            try{
                socket = new Socket("localhost", portNumber);
                os = socket.getOutputStream();
            }
            catch(IOException e){}
        }
        public void closeConnection(){
			try {
                os.close();
                socket.close();
			}
			catch (IOException e){}
        }
        
        @Override
        public void run() {
            newConnection();
            System.out.println("Server sending ... ");
            try {
                byte[] mybytearray = new byte[server.logic.ServerLogicImplement.choosePiecesSize()];
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                int bytesRead;
                 while((bytesRead = bis.read(mybytearray, 0, mybytearray.length)) != -1){
                  os.write(mybytearray, 0, bytesRead);
                  os.flush();
                }
                bis.close();
            } catch (EOFException ex) {}
            catch (UnknownHostException i){}
            catch (IOException i){}
         
            closeConnection();
        }
}
